﻿#if UNITY_EDITOR
using UnityEngine;
using System.Collections;
using UnityEditor;

public class HideItemOutOfView
{
    [MenuItem("Slg/一键隐藏视野外的MeshRenderer")]
    static void OneKeyHideItemOutOfView()
    {
        Transform[] trans = Selection.GetTransforms(SelectionMode.Unfiltered);
        for (int i = 0; i < trans.Length; i++)
        {
            HideItem(trans[i]);
        }
    }

    static void HideItem(Transform tran)
    {
        string meshRootName = "CombineMeshRoot";
        GameObject meshRoot = GameObject.Find(meshRootName);
        if (meshRoot == null) meshRoot = new GameObject(meshRootName);
        MeshRenderer[] meshArr = tran.GetComponentsInChildren<MeshRenderer>(true);
        for (int i = 0; i < meshArr.Length; i++)
        {
            MeshRenderer mesh = meshArr[i];
            Camera mainCam = Camera.main;
            Vector3 screenV3 = mainCam.WorldToScreenPoint(mesh.transform.position);
            bool show = (screenV3.x > -100 && screenV3.x < Screen.width + 100) && (screenV3.y > -100 && screenV3.y < Screen.height + 100);
            if (show)
            {
                mesh.transform.SetParent(meshRoot.transform);
            }
            if (show != mesh.gameObject.activeSelf)
            {

                mesh.gameObject.SetActive(show);
            }
        }
    }
}
#endif